<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\request;
use app\home\controller\Futures;

//开户交易
class Openanaccount extends Base{
    public function index(){
        $user = $this->userInformation();
        if($user['RNA']!=1){
            return "<script>alert('请先进行实名认证');window.location.href='".url('Certification/index')."'</script>";
        }
//        $data = Futures::publi();
        $qjgj = Db::name('futures_api')->where(['id'=>$user['fwq']])->find();
        $da = new Futures;
        if($qjgj['title']=='jt'){
            if($da->jitou()==1) return "<script>alert('期货账户有问题，请联系客服！');window.location.href='".url('home/certification/index')."'</script>";
            $userAllocation = Db::name('user_allocation')
                ->where('uid',$user['id'])
                ->where('status','1')
                ->find();
            if($userAllocation){
                return "<script>alert('已有配资方案');window.location.href='".url('Tradermng/index')."'</script>";
            }
        }else{
            if($da->publi()==1) return "<script>alert('期货账户有问题，请联系客服！');window.location.href='".url('home/certification/index')."'</script>";
            $userAllocation = Db::name('user_allocation')
                ->where('uid',$user['id'])
                ->where('status','1')
                ->find();
            if($userAllocation){
                return "<script>alert('已有配资方案');window.location.href='".url('Tradermng/index')."'</script>";
            }
        }
        $Allocation = Db::name('config')->where(['type'=>6])->select();
        $m = explode(',', $Allocation[0]['value']);
        $s = count($m);
        // dump($m);
        $this->assign('m',$m);
        $this->assign('s',$s);
        $this->assign('user',$user);

        return $this->fetch('Openanaccount/index');
    }
//		if($usertemp['RNA']!=1) return "<script>alert('请先进行实名认证');window.location.href='".url('Certification/index')."'</script>";
//        if($usertemp['balance'] <= '999.99') return "<script>alert('余额必须大于1000才能开户');window.location.href='".url('Recharge/recharge')."'</script>";
//        if($usertemp['assetaccount']!=null) return "<script>alert('不能重复开户');window.location.href='".url('Recharge/recharge')."'</script>";


    //开户申请资料提交
    public function accountApply(){
        $usertemp  = $this->userInformation();
        if($usertemp['RNA']!=1) return ['msg'=>'error_sm'];
        $min = Db::name('config')->where('key','khtj')->find()['value'];
        if($usertemp['balance'] < $min) return ['msg'=>'error_yue'];
        if($usertemp['assetaccount']!=null) return ['msg'=>'error_cf'];

        if($_POST['codes']!=Session::get('codes')){
            $this->error('资料已经提交请勿重复提交','Certification/index');
        }
        Session::set('codes',mt_rand(1000,9999));
        if($usertemp['assetaccount']==''||$usertemp['assetaccount']=='00000'){
            // 开户 and 实名
            $api=Db::name('futures_api')->alias('a')
                ->join('qfll_primary_account b','a.id=b.aid')
                ->field('a.*,b.account zzh,b.BrokderID,b.MonitorID')
                ->where('a.state',1)
                ->where('b.status',1)
                ->find();
            //dump($api);die;
            if($api['title']=='jt'){
            	
            }else{
                // 开户 and 实名
                $name=iconv("UTF-8", "GBK", $usertemp['name']);
                // 分组
                $agentsname=Db::name('agents')->field('group')->find($usertemp['aid'])['group'];
                $group=iconv("UTF-8", "GBK", $agentsname);
                $api=Db::name('futures_api')->field(true)->where('state',1)->find();
                // 主账号
                $mainaccount=Db::name('primary_account')->where('aid',$api['id'])->where('status',1)->find()['account'];
                // 期金管家接口地址
                $qjgjurl=$api['api'];
                // 期金管家账号
                $sa=$api['sa'];
                // 期金管家密码
                $sapass=$api['sapass'];
                $url=$qjgjurl.'createaccount?sa='.$sa.'&sapass='.$sapass.'&account=0&password='.$usertemp['password'].'&name='.$name.'&group='.$group.'&mainaccount='.$mainaccount;
                $res=https_request($url);
                $objectxml = simplexml_load_string($res);//将文件转换成 对象
                $xmljson= json_encode($objectxml );//将对象转换个JSON
                $xmlarray=json_decode($xmljson,true);//将json转换成数组
                //dump($xmlarray);die;
                if($xmlarray['Result']['Error']['Code']!=0){
                    return ['status'=>1,'msg'=>$xmlarray['Result']['Error']['Message']];
                }
                // 参考账号
                $source=$api['account'];
                $url=$qjgjurl.'setmarginrate?requestid=2&sa='.$sa.'&sapass='.$sapass.'&account='.$xmlarray['Result']['Account'].'&source='.$source;
                $res=https_request($url);
                $url=$qjgjurl.'setcommissionrate?requestid=3&sa='.$sa.'&sapass='.$sapass.'&account='.$xmlarray['Result']['Account'].'&source='.$source;
                $res=https_request($url);
                $url=$qjgjurl.'setriskcontrol?requestid=4&sa='.$sa.'&sapass='.$sapass.'&account='.$xmlarray['Result']['Account'].'&source='.$source;
                $res=https_request($url);
                if($xmlarray['Result']['Error']['Code']==0){
                    Db::name('users')->where('id',$usertemp['id'])->update(['assetaccount'=>$xmlarray['Result']['Account']]);
                    $open = [
                        'uid'=>$usertemp['id'],
                        'createtime'=>date('Y-m-d H:i:s'),
                        'status'=>1,
                        'completiontime'=>date('Y-m-d H:i:s'),
                        'examine'=>session('admin.name')
                    ];
                    Db::name('openanaccount')->insert($open);
                    return ['msg'=>'success','hao'=>$xmlarray['Result']['Account']];
                }
            }
        }else{
            return ['msg'=>'不满足开户条件'];
        }

    }

    //开户交易 提交配资
    public function Allocation(){
        $param = myarr($this->request->post());
        $time = Db::name('config')->where('key','jstime')->find()['value'];
        $s = explode('-',$time);
        $da = time();
        if($da >= strtotime(date("Y-m-d $s[0]")) && $da <= strtotime(date("Y-m-d $s[1]"))) return json_encode(['msg'=>"$s[0]~$s[1]时为结算时间，不允许出入金"],JSON_UNESCAPED_UNICODE);
        if(preg_match("/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/",$param['mXzzj']) != 1) return json_encode(['msg'=>'金额格式错误'],JSON_UNESCAPED_UNICODE);
        if(preg_match("/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/",$param['chosseMon']) != 1) return json_encode(['msg'=>'金额格式错误'],JSON_UNESCAPED_UNICODE);
        if($param['mXzzj']/$param['chosseMon'] < 1/10 || $param['mXzzj'] < 1000) return json_encode(['msg'=>'配资金额错误'],JSON_UNESCAPED_UNICODE);

        $user = $this->userInformation();
        if($user['balance'] < $param['mXzzj']) return json_encode(['msg'=>'账户余额不足请充值'],JSON_UNESCAPED_UNICODE);
        // return json_encode($param['chosseMon']);
        $userAllocation = Db::name('user_allocation')
            ->where('uid',$user['id'])
            ->where('status',1)
            ->find();
        if($userAllocation) return json_encode(['msg'=>'该账户正在操盘中请先关闭'],JSON_UNESCAPED_UNICODE);
        if(Session::get('codes')!=$param['codes']) return json_encode(['msg'=>'系统正在处理中求请勿重复提交'],JSON_UNESCAPED_UNICODE);
        Session::set('codes',mt_rand(1000,9999));
        $Allocation = Db::name('allocation')->where('id',1)->find();
        // $yj = $Allocation['Earlywarningbase']/$Allocation['Marginbase'];//预警基数
        // $zs = $Allocation['Shopbase']/$Allocation['Marginbase']; //止损基数
        $datas = [
            'uid' => $user['id'],
            'bond'=> $param['mXzzj'],
            'allocation'=>$param['chosseMon'],
            'transactionamount' =>$param['mXzzj']+$param['chosseMon'],
            // 'warningamount' => $param['mXzzj']*$yj+$param['chosseMon'],
            // 'shopamount' => $param['mXzzj']*$zs+$param['chosseMon'],
            'warningamount' => $param['chosseMon']+$param['chosseMon']*($Allocation['Earlywarningbase']/10000),
            'shopamount' => $param['chosseMon']+$param['chosseMon']*($Allocation['Shopbase']/10000),
            'status'=>1,
            'futuresID'=> $user['assetaccount'],
            'disktime' => date('Y-m-d H:i:s'),
        ];
        // 启动事务
        Db::startTrans();
        try{

            $newmoney = $user['balance'] - $param['mXzzj'];
            $upuser = Db::name('users')
                ->where(['id'=>$user['id']])
                ->update(['balance'=>$newmoney]);
            if(!$upuser) return json_encode(['msg'=>'操作错误'],JSON_UNESCAPED_UNICODE);
            header("Content-type: text/html; charset=utf-8");
            $requestid=6;//用户结果与请求统一的值
            // $sa='qjgj';//期货管理员账号
            // $sapass='123';//期货管理员密码
            $account=$user['assetaccount'];
            $amount=$param['mXzzj']+$param['chosseMon'];//入金金额
            $credit=$param['chosseMon'];//优先资金
            $remark=iconv("UTF-8", "GBK", '配资操盘');
//        $qjgj = Db::name('futures_api')->where(['state'=>1])->find();
            $qjgj = Db::name('futures_api')->where(['id'=>$user['fwq']])->find();
            if($qjgj['title']=='jt'){

            }else{
                // return json_encode($qjgj);
                // $url="https://moni.byxgj.com:13134/deposit?requestid=$requestid&sa=$sa&sapass=$sapass&account=$account&amount=$amount&credit=$credit&remark=$remark";
                $url="{$qjgj['api']}deposit?requestid=$requestid&sa={$qjgj['sa']}&sapass={$qjgj['sapass']}&account=$account&amount=$amount&credit=$credit&remark=$remark";
                $curl = curl_init(); // 启动一个CURL会话
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
                $tmpInfo = curl_exec($curl);     //返回api的json对象
                //关闭URL请求
                curl_close($curl);
                $arr = simplexml_load_string($tmpInfo);
                $xmljson= json_encode($arr );//将对象转换个JSON
                $xmlarray=json_decode($xmljson,true);//将json转换成数组
                $ar=$xmlarray['Result'];
                if(!isset($ar)){
                    return "<script>alert('期货账户有问题，请联系客服！');window.location.href='".url('home/Deposit/deposit')."'</script>";
                }
            }
            //出入金记录
            $list=array();
            $list['uid']=$user['id'];
            $list['futuresID']=$account;
            $list['eae']=1;
            $list['amount']='-'.$param['mXzzj'];
            $list['del']=$ar['Error']['Code'];
            // $list['remakes']='账户转期货';
            $list['remakes']='配资操盘';

            // $list['time'] = date('Y-m-d H:s:i');
            // return json_encode($list);
            $res = $this->find_log_balance($user['id']);
            //是否入金成功 0是入金成功
            if($ar['Error']['Code']==0){
                //入金成功扣除余额
                $price=$user['balance']-$param['mXzzj'];
                //资金日志
                $dat=array();
                $dat['uid']=$user['id'];
                $dat['type']=5;
                $dat['price']='-'.$param['mXzzj'];
                // $dat['balance']=$price;
                $dat['balance']=$res-$param['mXzzj'];

                //期货配资资金记录
                $allocation = [
                    'uid' => $user['id'],
                    'futuresID'=>$account,
                    'priorityfunds'=>$param['chosseMon'],
                    'eae'=>1,//入金
                    'state'=>$ar['Error']['Code'],//成功或者失败
                ];
                    Db::name('allocationpriority')->insert($allocation);
                    Db::name('user_futures')->insert($list);
                    $ins = Db::name('user_allocation')->insert($datas);//添加配资
                    $a = Db::name('cashlog')->insert($dat);

                    Db::commit();
//                    //回滚事务
//                    Db::rollback();
//                    return json_encode(['msg'=>'执行失败'],JSON_UNESCAPED_UNICODE);
                return json_encode(['msg'=>'success'],JSON_UNESCAPED_UNICODE);
            }else{
                Db::rollback();
                return json_encode(['msg'=>$ar['Error']['Message']],JSON_UNESCAPED_UNICODE);
            }
        } catch (\Exception $e) {
            //回滚事务
//            var_dump($e);die;
            Db::rollback();
            return json_encode(['msg'=>$e->getMessage()],JSON_UNESCAPED_UNICODE);
        }

    }

    /**
     * @param $account：待出入金的子账号
     * @param $amount：总金额（劣后+优先），正值表示入金，负值表示出金；
     * @param $credit：总金额中的优先资金部分，正值表示入金，负值表示出金
     * remark：备注（直接使用GBK编码）
     */
    //出金
    // public function


    /**
     * @param $account：待出入金的子账号
     * @param $amount：总金额（劣后+优先），正值表示入金，负值表示出金；
     * @param $credit：总金额中的优先资金部分，正值表示入金，负值表示出金
     * remark：备注（直接使用GBK编码）
     */
    //开始操盘
    static public function operate(){

        //此账号是否开户
        $user = Db::name('users')->where('id',Session::get('uid'))->field('id,assetaccount,balance')->find();
        $userAllocation = Db::name('user_allocation')
            ->where('uid',$user['id'])
            ->where('status','not in','2')
            ->find();
        // ->filed('assetaccount,balance');
        // dump($user);die;
        //var_dump($ste);

    }
}